package com.simplecontact.providers;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import com.simplecontact.R;
import com.simplecontact.classes.Contact;
import com.simplecontact.classes.ContactDb;
import com.simplecontact.databases.ContactDbOpenHelper;

public class ContactProvider extends ContentProvider {

	private ContactDbOpenHelper dbsur;
	private static final UriMatcher sUriMatcher;
	private static HashMap<String, String> sDicProjectionMap;
	
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = dbsur.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case 1:
            count = db.delete(Contact.CONTACT_TABLE_NAME, where, whereArgs);
            break;

        case 2:
            String surId = uri.getPathSegments().get(1);
            count = db.delete(Contact.CONTACT_TABLE_NAME, Contact.ContactColumns._ID + "=" + surId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
        case 1:        
            return Contact.ContactColumns.CONTENT_TYPE;
        case 2:
            return Contact.ContactColumns.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		if (sUriMatcher.match(uri) != 1) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }       

        if (values.containsKey(Contact.ContactColumns.NICKNAME) == false) {
            Resources r = Resources.getSystem();
            values.put(Contact.ContactColumns.NICKNAME, r.getString(R.string.strUnnamed));
        }

        if (values.containsKey(Contact.ContactColumns.FIRSTNAME) == false) {
            values.put(Contact.ContactColumns.FIRSTNAME, "");
        }

        if (values.containsKey(Contact.ContactColumns.LASTNAME) == false) {
            values.put(Contact.ContactColumns.LASTNAME, "");
        }
        
        if (values.containsKey(Contact.ContactColumns.EMAIL) == false) {
            values.put(Contact.ContactColumns.EMAIL, "");
        }
        
        if (values.containsKey(Contact.ContactColumns.PHONENUMBER) == false) {
            values.put(Contact.ContactColumns.PHONENUMBER, "");
        }
        
        if (values.containsKey(Contact.ContactColumns.IMAGE) == false) {
            values.put(Contact.ContactColumns.IMAGE, "");
        }
        
        if (values.containsKey(Contact.ContactColumns.ADDRESS) == false) {
            values.put(Contact.ContactColumns.ADDRESS, "");
        }
        SQLiteDatabase db = dbsur.getWritableDatabase();
        long rowId = db.insert(Contact.CONTACT_TABLE_NAME, Contact.ContactColumns._ID, values);
        if (rowId > 0) {
            Uri surUri = ContentUris.withAppendedId(Contact.ContactColumns.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(surUri, null);
            return surUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		dbsur = new ContactDbOpenHelper(getContext(), ContactDb.CONTACT_DATABASE_NAME, null, ContactDb.DATABASE_VERSION);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(Contact.CONTACT_TABLE_NAME);

        switch (sUriMatcher.match(uri)) {
        case 1:
            qb.setProjectionMap(sDicProjectionMap);
            break;
        case 2:
            qb.setProjectionMap(sDicProjectionMap);
            qb.appendWhere(Contact.ContactColumns._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = Contact.ContactColumns.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        // Get the database and run the query
        SQLiteDatabase db = dbsur.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		SQLiteDatabase db = dbsur.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case 1:
            count = db.update(Contact.CONTACT_TABLE_NAME, values, where, whereArgs);
            break;
        case 2:
            String surId = uri.getPathSegments().get(1);
            count = db.update(Contact.CONTACT_TABLE_NAME, values, Contact.ContactColumns._ID + "=" + surId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Contact.AUTHORITY, "contact", 1);
        sUriMatcher.addURI(Contact.AUTHORITY, "contact/#", 2);        

        sDicProjectionMap = new HashMap<String, String>();
        sDicProjectionMap.put(Contact.ContactColumns._ID, Contact.ContactColumns._ID);
        sDicProjectionMap.put(Contact.ContactColumns.NICKNAME, Contact.ContactColumns.NICKNAME);
        sDicProjectionMap.put(Contact.ContactColumns.FIRSTNAME, Contact.ContactColumns.FIRSTNAME);
        sDicProjectionMap.put(Contact.ContactColumns.LASTNAME, Contact.ContactColumns.LASTNAME);
        sDicProjectionMap.put(Contact.ContactColumns.EMAIL, Contact.ContactColumns.EMAIL);
        sDicProjectionMap.put(Contact.ContactColumns.PHONENUMBER, Contact.ContactColumns.PHONENUMBER);
        sDicProjectionMap.put(Contact.ContactColumns.IMAGE, Contact.ContactColumns.IMAGE);
        sDicProjectionMap.put(Contact.ContactColumns.ADDRESS, Contact.ContactColumns.ADDRESS);
    }
}
